package com.xj.ucg2webapi;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

@RestController
public class SayHelloController {
    /**
     * 测试1
     * @param msg
     * @param req
     * @return
     */
    @GetMapping("say")
    public String say(String msg,String who, HttpServletRequest req){
        System.out.println("msg:"+msg);
        //通过getHeaderNames获得所有头名字的Enumeration集合
        System.out.println("----------header内容输出------");
        Enumeration<String> headNames = req.getHeaderNames();

        while(headNames.hasMoreElements()){

            String headName = headNames.nextElement();

            System.out.println(headName+":"+req.getHeader(headName));

        }
        return "收到消息:-->>>"+msg+"<<<--msg="+msg;
    }

    /**
     * 测试2、3
     * @param msg
     * @param req
     * @return
     */
    @PostMapping("postTest")
    public String postTest(String msg,String who, HttpServletRequest req){
        System.out.println("msg:"+msg);
        //通过getHeaderNames获得所有头名字的Enumeration集合
        System.out.println("----------header内容输出------");
        Enumeration<String> headNames = req.getHeaderNames();

        while(headNames.hasMoreElements()){

            String headName = headNames.nextElement();

            System.out.println(headName+":"+req.getHeader(headName));

        }
        return "收到消息:-->>>"+msg+"<<<--  who="+who;
    }

    /**
     * postJson参数
     * @param param
     * @param req
     * @return
     */
    @PostMapping("postJsonTest")
    public String postJsonTest(@RequestBody Map<String,String> param, HttpServletRequest req){
        //通过getHeaderNames获得所有头名字的Enumeration集合
        System.out.println("----------header内容输出------");
        Enumeration<String> headNames = req.getHeaderNames();

        while(headNames.hasMoreElements()){

            String headName = headNames.nextElement();

            System.out.println(headName+":"+req.getHeader(headName));

        }
        return "收到消息:-->>>"+param+"<<<--";
    }

    /**
     * 文件上传+参数
     * @param file
     * @param filename
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file,@RequestParam("filename") String filename) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        System.out.println("参数：filename="+filename);
        String fileName = file.getOriginalFilename();
        String filePath = "D:\\test";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
        }
        return "上传失败！";
    }
}
